package csharp.cauth.listeners;

import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityListener;
import org.bukkit.event.entity.EntityTargetEvent;

import csharp.cauth.CAuth;

/**
 * @author Ярослав (CSharp) Simple entity listener.
 */
public class CAEntityListener extends EntityListener
{
	private final CAuth plugin;

	public CAEntityListener(CAuth instance)
	{
		plugin = instance;
	}

	@Override
	public void onEntityDamage(EntityDamageEvent event)
	{
		Entity ent = event.getEntity();

		if (ent instanceof Player)
		{
			Player player = (Player) ent;

			if (!CAuth.authorized.contains(player))
			{
				event.setCancelled(true);
			}
			else
			{
				if (event instanceof EntityDamageByEntityEvent)
				{
					EntityDamageByEntityEvent evt = (EntityDamageByEntityEvent) event;
					Entity damager = evt.getDamager();

					if (damager instanceof Player)
					{
						Player damagerPlayer = (Player) damager;

						if (!CAuth.authorized.contains(damagerPlayer))
						{
							event.setCancelled(true);
						}
					}
				}
			}
		}
		else
		{
			if (event instanceof EntityDamageByEntityEvent)
			{
				EntityDamageByEntityEvent evt = (EntityDamageByEntityEvent) event;
				Entity damager = evt.getDamager();

				if (damager instanceof Player)
				{
					Player damagerPlayer = (Player) damager;

					if (!CAuth.authorized.contains(damagerPlayer))
					{
						event.setCancelled(true);
					}
				}
			}
		}
	}

	@Override
	public void onEntityTarget(EntityTargetEvent event)
	{
		Entity ent = event.getTarget();

		if (ent instanceof Player)
		{
			Player player = (Player) ent;

			if (!CAuth.authorized.contains(player))
			{
				event.setCancelled(true);
			}
		}
	}
}
